<template>
  <div class="app-container">
    <div class="titleBox">
      <div style="border: 1px; background-color: #4e8dff; width: 6px; height: 20px"></div>
      <span style="margin-left: 10px; ">{{ title }}</span>
    </div>
    <el-form
      ref="form"
      v-loading="formLoading"
      :model="form"
      :rules="rules"
      size="small"
      label-width="160px"
    >
      <p style="padding-left: 20px;">基本信息</p>
      <el-row type="flex" style="flex-wrap: wrap; ">
        <el-col :span="8">
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-emoji
              v-model="form.userName"
              placeholder="请输入姓名"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio-button
                v-for="dict in sysUserSexList"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="民族" prop="nation">
            <el-select
              v-model="form.nation"
              placeholder="请选择民族"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in nationList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出生年月" prop="birthday">
            <el-date-picker
              v-model="form.birthday"
              type="month"
              format="yyyy.MM"
              value-format="yyyy.MM"
              placeholder="请选择出生年月"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="政治面貌" prop="politicsOutlook">
            <el-select
              v-model="form.politicsOutlook"
              placeholder="请选择政治面貌"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in politicsOutlookList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证号" prop="idcard">
            <el-input
              v-emoji
              v-model="form.idcard"
              placeholder="请输入身份证号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="籍贯" prop="nativePlace">
            <el-input
              v-model="form.nativePlace"
              placeholder="请输入籍贯"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="婚姻状况" prop="maritalStatus">
            <el-select v-model="form.maritalStatus" placeholder="请选择婚姻状况" clearable style="width: 100%">
              <el-option
                v-for="dict in maritalStatusList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="家庭住址" prop="homeAddress">
            <el-input
              v-model="form.homeAddress"
              placeholder="具体到门牌号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="通讯地址" prop="mailAddress">
            <el-input
              v-model="form.mailAddress"
              placeholder="具体到门牌号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="参加工作时间" prop="workTime">
            <el-date-picker
              v-model="form.workTime"
              type="date"
              placeholder="请选择参加工作时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="进入昌泰集团时间" prop="entryTime">
            <el-date-picker
              v-model="form.entryTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择进入昌泰集团时间"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="进入本公司时间" prop="joinCompanyTime">
            <el-date-picker
              v-model="form.joinCompanyTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择进入本公司时间"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="现工作单位" prop="nowUnitId">
            <div class="org-field" @click="openOrgTree('2')">
              {{ nowUnitName }}
              <span v-if="!nowUnitName" style="color: #ccc">请选择现工作单位</span>
              <span class="icon-right el-icon-arrow-right"></span>
              <span
                class="el-tag__close el-icon-close icon-close"
                @click.stop="clearOrgValue('2')"
                v-if="nowUnitName"
              ></span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门" prop="deptId">
            <div class="org-field" @click="openOrgTree('3')">
              {{ deptName }}
              <span v-if="!nowUnitName" style="color: #ccc">请选择部门</span>
              <span class="icon-right el-icon-arrow-right"></span>
              <span
                class="el-tag__close el-icon-close icon-close"
                @click.stop="clearOrgValue('3')"
                v-if="deptName"
              ></span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="劳动关系所在单位" prop="relationUnitId">
            <div class="org-field" @click="openOrgTree('1')">
              <span class="org-field-value">
                {{ relationUnitName }}
                <span v-if="!nowUnitName" style="color: #ccc">请选择劳动关系所在单位</span>
              </span>
              <span class="icon-right el-icon-arrow-right"></span>
              <span
                class="el-tag__close el-icon-close icon-close"
                @click.stop="clearOrgValue('1')"
                v-if="relationUnitName"
              ></span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="dutyName">
            <el-input
              v-emoji
              v-model="form.dutyName"
              placeholder="请输入职务"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任现职务时间" prop="dutyTime">
            <el-date-picker
              v-model="form.dutyTime"
              type="date"
              placeholder="请选择任现职务时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用工形式" prop="employType">
            <el-select
              v-model="form.employType"
              placeholder="用工形式"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in sysEmployTypeList"
                :key="dict.value"
                :label="dict.label"
                :value="Number(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职级" prop="ranking">
            <el-select v-model="form.ranking" placeholder="请选择职级" clearable style="width: 100%">
              <el-option-group
                v-for="group in rankingOptions"
                :key="group.label"
                :label="group.label">
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任现职级时间" prop="rankingTime">
            <el-date-picker
              v-model="form.rankingTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择任现职级时间"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所在党支部" prop="partyBranch">
            <el-input
              v-model="form.partyBranch"
              placeholder="请输入所在党支部"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入党时间" prop="joinPoliticalTime">
            <el-date-picker
              v-model="form.joinPoliticalTime"
              type="date"
              placeholder="请选择入党时间"
              :picker-options="datePickerValid"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="转正时间" prop="confirmationTime">
            <el-date-picker
              v-model="form.confirmationTime"
              type="date"
              placeholder="请选择转正时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="党内职务" prop="partyTitle">
            <el-input
              v-model="form.partyTitle"
              placeholder="请输入党内职务"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户标签" prop="userTip">
            <el-select
              v-model="form.userTip"
              multiple
              placeholder="请选择用户标签"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="val in userTipOptions"
                :key="val.id"
                :label="val.name"
                :value="val.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户类型" prop="userCategory">
            <el-select
              v-model="form.userCategory"
              multiple
              :multiple-limit="1"
              placeholder="请选择用户类型"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="val in sysUserCategoryList"
                :key="val.value"
                :label="val.label"
                :value="val.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <p style="padding-left: 20px;">账号信息</p>
      <el-row type="flex" style="flex-wrap: wrap; ">
        <el-col :span="8">
          <el-form-item label="工号" prop="jobNumber">
            <el-input
              v-emoji
              v-model="form.jobNumber"
              placeholder="请输入工号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号" prop="phonenumber">
            <el-input
              autocomplete="new-password"
              v-model="form.phonenumber"
              placeholder="手机号作为登录账号，修改后，用新的手机号登录保留原有账号信息"
              show-word-limit
              maxlength="11"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="userId === undefined">
          <el-form-item label="登录密码" prop="addPassword">
            <el-input
              autocomplete="new-password"
              v-model="form.addPassword"
              placeholder="请输入登录密码"
              type="password"
              maxlength="20"
              show-password
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="userId !== undefined">
          <el-form-item label="登录密码" required>
            <el-input
              autocomplete="new-password"
              v-model="form.editPassword"
              placeholder="如果你编辑密码，不填写，则不修改"
              type="password"
              maxlength="20"
              show-password
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上级主管" prop="superiorId">
            <el-input
              v-model="form.superiorName"
              @click.native="openUserPicker"
              placeholder="请选择上级主管"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属角色" style="height: 50px" prop="roleIds">
            <el-select
              v-model="form.roleIds"
              multiple
              :multiple-limit="1"
              placeholder="如果你选择了角色，则此用户本身就继承了此角色的所有权限"
              style="width: 100%"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio-button
                v-for="dict in sysNormalDisableList"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="数据权限" prop="dataAuthType">
            <el-radio-group
              v-model="form.dataAuthType"
              @change="dataAuthTypeChangeHandler"
            >
              <el-radio-button
                v-for="dict in sysDataAuthList"
                :key="Number(dict.value)"
                :label="Number(dict.value)"
              >{{ dict.label }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="showDataAuthBool">
        <el-col :span="8" >
          <el-form-item label="" prop="dataAuthId">
            <el-input
              v-model="dataAuthNames"
              placeholder="请选择部门"
              @focus="openOrgTree('4')"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <p style="padding-left: 20px;">个人积分</p>
      <el-row type="flex" style="flex-wrap: wrap; ">
        <el-col :span="8">
          <el-form-item label="历史积分" prop="historyScore">
            <el-input-number v-model="form.historyScore" :max="9999" label="请输入历史积分" :step="1" :step-strictly="true" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="2025年积分" prop="score2025">
            <el-input-number v-model="form.score2025" :max="9999" label="请输入2025年积分" :step="1" :step-strictly="true" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>


      <p style="padding-left: 20px;">个人简历</p>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">学习经历</div>
        <div style="width: 90%">
          <elx-editable
            ref="educationalEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{school: [{required: true, message: '请输入学校', trigger: 'blur'}]}"
            :data.sync="educationalBackgrounds"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.educationalEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.educationalEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="startTime"
              label="开始时间"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
            <elx-editable-column
              prop="endTime"
              label="结束时间"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
            <elx-editable-column
              prop="school"
              label="学校"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="major"
              label="专业"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="format"
              label="学习形式"
              :edit-render="{name: 'ElSelect', type: 'visible', options: formatList}"></elx-editable-column>
            <elx-editable-column
              prop="academic"
              label="学历"
              :edit-render="{name: 'ElSelect', type: 'visible', options: academicList}"></elx-editable-column>
            <elx-editable-column
              prop="degree"
              label="学位"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="isHighest"
              label="是否最高学历"
              :edit-render="{name: 'ElSwitch', type: 'visible', props: {'activeValue': 'Y', 'inactiveValue': 'N'}}"
            ></elx-editable-column>
          </elx-editable>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">工作经历</div>
        <div style="width: 90%">
          <elx-editable
            ref="workExperienceEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{unit: [{required: true, message: '请输入工作单位', trigger: 'blur'}]}"
            :data.sync="workExperience"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.workExperienceEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.workExperienceEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="startTime"
              label="开始时间"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
            <elx-editable-column
              prop="endTime"
              label="结束时间"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
            <elx-editable-column
              prop="unit"
              label="工作单位"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="department"
              label="部门"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="position"
              label="职务"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="leaveReason"
              label="离职原因"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="type"
              label="人员类型"
              :edit-render="{name: 'ElSelect', type: 'visible', options: sysEmployTypeList}"></elx-editable-column>
            <elx-editable-column
              prop="isPartTime"
              label="是否兼职"
              :edit-render="{name: 'ElSwitch', type: 'visible', props: {'activeValue': 'Y', 'inactiveValue': 'N'}}">
            </elx-editable-column>
          </elx-editable>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">劳动合同</div>
        <div style="width: 90%">
          <elx-editable
            ref="contractEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{startTime: [{required: true, message: '请输入开始时间', trigger: 'blur'}]}"
            :data.sync="laborContracts"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.contractEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.contractEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="startTime"
              label="开始时间"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
            <elx-editable-column
              prop="endTime"
              label="结束时间"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
            <elx-editable-column
              prop="renewals"
              label="续签次数"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="type"
              label="合同类型"
              :edit-render="{name: 'ElSelect', type: 'visible', options: contractTypeList}"></elx-editable-column>
            <elx-editable-column
              prop="term"
              label="合同期限"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="signUnit"
              label="合同签订单位"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
          </elx-editable>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">职称</div>
        <div style="width: 90%">
          <elx-editable
            ref="titlesEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{name: [{required: true, message: '请输入职称名称', trigger: 'blur'}]}"
            :data.sync="titles"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.titlesEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.titlesEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="name"
              label="名称"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="grade"
              label="等级"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="profession"
              label="专业"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="assessmentTime"
              label="评定时间"
              width="260"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
          </elx-editable>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">职业资格</div>
        <div style="width: 90%">
          <elx-editable
            ref="professionalEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{name: [{required: true, message: '请输入名称', trigger: 'blur'}]}"
            :data.sync="professionalQualifications"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.professionalEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.professionalEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="name"
              label="名称"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="level"
              label="等级"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="obtainingTime"
              label="获得时间"
              width="260"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
          </elx-editable>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">奖惩信息</div>
        <div style="width: 90%">
          <elx-editable
            ref="rewardPunishmentsEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{name: [{required: true, message: '请输入奖惩名称', trigger: 'blur'}]}"
            :data.sync="rewardPunishments"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.rewardPunishmentsEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.rewardPunishmentsEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="time"
              label="获奖/惩处时间"
              width="260"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'month', format: 'yyyy.MM', valueFormat: 'yyyy.MM'}}"></elx-editable-column>
            <elx-editable-column
              prop="name"
              label="名称"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="unitName"
              label="所属单位"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="level"
              label="奖惩级别"
              width="260"
              :edit-render="{name: 'ElSelect', type: 'visible', options: rewardLevelList}"></elx-editable-column>
          </elx-editable>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">家庭成员</div>
        <div style="width: 90%">
          <elx-editable
            ref="familyEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{name: [{required: true, message: '请输入姓名', trigger: 'blur'}]}"
            :data.sync="familyMembers"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.familyEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.familyEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="name"
              label="姓名"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="relationship"
              label="与本人关系"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="birthday"
              label="出生日期"
              width="260"
              :edit-render="{name: 'ElDatePicker', type: 'visible', props: {type: 'date', format: 'yyyy.MM.dd', valueFormat: 'yyyy.MM.dd'}}"></elx-editable-column>
            <elx-editable-column
              prop="unit"
              label="工作单位及职务"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
          </elx-editable>
        </div>
      </div>
      <div style="display: flex; margin-bottom: 10px;">
        <div class="el-form-item__label label">紧急联系人</div>
        <div style="width: 90%">
          <elx-editable
            ref="emergencyEditable"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :edit-rules="{name: [{required: true, message: '请输入姓名', trigger: 'blur'}]}"
            :data.sync="emergencyContacts"
          >
            <elx-editable-column width="60">
              <template #header>
                <i class="el-icon-circle-plus-outline columnIcon" @click="$refs.emergencyEditable.insert()"></i>
              </template>
              <template #default="{row}">
                <i class="el-icon-delete columnIcon" @click="$refs.emergencyEditable.remove(row)" style="color: red;"></i>
              </template>
            </elx-editable-column>
            <elx-editable-column
              prop="name"
              label="姓名"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="relationship"
              label="与本人的关系"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
            <elx-editable-column
              prop="contactNumber"
              label="联系电话"
              width="260"
              :edit-render="{name: 'ElInput', type: 'visible'}"></elx-editable-column>
          </elx-editable>
        </div>
      </div>

    </el-form>
    <div style="margin: 2% auto auto 40%">
      <el-button class="form_button_item" @click="closeBtnHandler"
      >取消
      </el-button
      >
      <el-button
        class="form_button_item"
        :loading="saveBtnLoading"
        type="primary"
        @click="submitForm"
      >保存
      </el-button>
    </div>
    <user-picker
      ref="userPickerRef"
      :isMultiple="false"
      :isCheck="true"
      @submit="userPickerResult"
      :value="backUserIds"
    ></user-picker>

    <org-tree
      :orgType="orgType"
      :nowUnitId="form.nowUnitId"
      :orgData="orgData"
      v-if="showOrgTree"
      :show="showOrgTree"
      @close="showOrgTree = false"
      @save="saveOrgValue"
      :title="orgTitle"
      :orgIds="orgIds"
    ></org-tree>
  </div>
</template>

<script>
import orgTree from "@/components/orgTree";
import Treeselect from "@riophae/vue-treeselect";
import {addUser, getDepartments, getUser, updateUser} from "@/api/system/user";
import {treeselect, treeselectAll} from "@/api/system/dept";
import {listTip} from "@/api/system/tip/tipApi";
import userPicker from "@/views/system/user/picker/index";
import {getDictsAll, getDicts} from "@/api/system/dict/data";
import {listRoleSimple} from "@/api/system/role"

export default {
  name: "UserAdd",
  components: {Treeselect, userPicker, orgTree},
  data() {
    return {
      datePickerValid: {
        disabledDate(time) {
          return time.getTime() >= Date.now();
        },
      },
      backUserIds: [],
      dataAuthNames: "",
      formLoading: false,
      showDataAuthBool: false,
      deptPickerOpen: false,
      userId: undefined,
      form: {},

      educationalBackgrounds:[],
      workExperience: [],
      laborContracts: [],
      titles: [],
      professionalQualifications: [],
      rewardPunishments: [],
      familyMembers: [],
      emergencyContacts: [],

      title: "",
      // 部门树选项
      deptOptions: [],
      // 用户选项
      userTipOptions: [],
      // 默认密码
      initPassword: undefined,
      // 角色选项
      roleOptions: [],
      saveBtnLoading: false,
      rules: {
        userName: [
          {required: true, message: "请输入姓名", trigger: "blur"},
          {
            min: 2,
            max: 20,
            message: "姓名长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        sex: [{required: true, message: "请选择性别", trigger: "blur"}],
        idcard: [
          {
            required: true,
            pattern:
              /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入正确的身份证号",
            trigger: "blur",
          },
        ],
        politicsOutlook: [
          {required: true, message: "请选择政治面貌", trigger: "blur"},
        ],
        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        relationUnitId: [
          {
            required: true,
            message: "请选择劳动关系所在单位",
            trigger: "change",
          },
        ],
        nowUnitId: [
          {required: true, message: "请选择现工作单位", trigger: "change"},
        ],
        deptId: [{required: true, message: "请选择部门", trigger: "change"}],
        dutyName: [
          {required: true, message: "请输入职务", trigger: "blur"},
          {max: 20, message: "职务不可超过20字", trigger: "blur"},
        ],
        employType: [
          {required: true, message: "请选择用工形式", trigger: "change"},
        ],
        addPassword: [
          {required: true, message: "登录密码不能为空", trigger: "blur"},
          {
            min: 5,
            max: 20,
            message: "登录密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        roleIds: [{required: true, message: "请选择角色", trigger: "change"}],
        userTip: [
          {required: true, message: "请选择用户标签", trigger: "change"},
        ],
        userCategory: [
          {required: true, message: "请选择用户类型", trigger: "change"},
        ],
        dataAuthType: [
          {required: true, message: "请选择数据权限", trigger: "change"},
        ],
        dataAuthId: [
          {required: true, message: "请选择数据权限", trigger: "change"},
        ],
      },

      showOrgTree: false,
      orgType: "",
      orgTitle: "",
      orgData: [],
      relationUnitName: "",
      nowUnitName: "",
      deptName: "",
      orgIds: [],

      rankingOptions: [],
      sysNormalDisableOptions: [],
      sysUserSexOptions: [],
      sysUserCategoryOptions: [],
      sysEmployTypeOptions: [],
      sysDataAuthOptions: [],
      maritalStatusOptions: [],
      nationOptions: [],
      politicsOutlookOptions: [],
      formatOptions: [],
      academicOptions: [],
      contractTypeOptions : [],
      rewardLevelOptions: []
    };
  },
  created() {
    this.initPage();
    getDicts("ranking").then(res => {
      if (res.code == 200) {
        this.rankingOptions = res.data
      }
    });
    getDictsAll({'dictTypeAll': ["sys_normal_disable", "sys_user_sex", "sys_employ_type", "sys_user_category", "sys_data_auth",
        "marital_status", "nation", "politics_outlook", "format", "academic", "contract_type", "reward_level"]}).then(res => {
      if (res.code == 200) {
        this.$set(this, "sysNormalDisableOptions", res.data["sys_normal_disable"]);
        this.$set(this, "sysUserSexOptions", res.data["sys_user_sex"]);
        this.$set(this, "sysEmployTypeOptions", res.data["sys_employ_type"]);
        this.$set(this, "sysUserCategoryOptions", res.data["sys_user_category"]);
        this.$set(this, "sysDataAuthOptions", res.data["sys_data_auth"]);
        this.$set(this, "maritalStatusOptions", res.data["marital_status"]);
        this.$set(this, "nationOptions", res.data["nation"]);
        this.$set(this, "politicsOutlookOptions", res.data["politics_outlook"]);
        this.$set(this, "formatOptions", res.data["format"]);
        this.$set(this, "academicOptions", res.data["academic"]);
        this.$set(this, "contractTypeOptions", res.data["contract_type"]);
        this.$set(this, "rewardLevelOptions", res.data["reward_level"]);
      }
    });
  },
  computed: {
    sysNormalDisableList: function () {
      if (this.sysNormalDisableOptions) {
        return this.sysNormalDisableOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    sysUserSexList: function () {
      if (this.sysUserSexOptions) {
        return this.sysUserSexOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    sysEmployTypeList: function () {
      if (this.sysEmployTypeOptions) {
        return this.sysEmployTypeOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    sysUserCategoryList: function () {
      if (this.sysUserCategoryOptions) {
        return this.sysUserCategoryOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    sysDataAuthList: function () {
      if (this.sysDataAuthOptions) {
        return this.sysDataAuthOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    maritalStatusList: function () {
      if (this.maritalStatusOptions) {
        return this.maritalStatusOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    nationList: function () {
      if (this.nationOptions) {
        return this.nationOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    politicsOutlookList: function () {
      if (this.politicsOutlookOptions) {
        return this.politicsOutlookOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    formatList: function () {
      if (this.formatOptions) {
        return this.formatOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    academicList: function () {
      if (this.academicOptions) {
        return this.academicOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    contractTypeList: function () {
      if (this.contractTypeOptions) {
        return this.contractTypeOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
    rewardLevelList: function () {
      if (this.rewardLevelOptions) {
        return this.rewardLevelOptions.map(item => {
          return {label: item.dictLabel, value: item.dictValue, key: item.dictValue};
        })
      } else {
        return [];
      }
    },
  },
  methods: {
    initPage() {
      this.reset();
      this.getTreeselect();
      this.getSysUserTip();
      const param = this.$route.params.id;
      if (param != 0 && param != "0") {
        this.title = "编辑用户";
        this.userId = this.$route.params.id;
      } else {
        this.title = "新增用户";
      }
      listRoleSimple({
        pageNum: 1,
        pageSize: 1000,
        filterAdmin: true,
      }).then((response) => {
        this.roleOptions = response.rows;
        this.getUserInfo();
      });
    },
    idCardValid(val){
      const idCard= val.replace(/^(\d{6})\d+(\d{4})$/, "$1******$2")
      console.log(idCard)
      return idCard
    },
    getUserInfo() {
      this.reset();
      if (this.userId) {
        this.formLoading = true;
        getUser(this.userId)
          .then((response) => {
            this.form = response.data;
            this.backUserIds.push(response.data.superiorId);
            this.relationUnitName = response.data.relationUnitName;
            this.nowUnitName = response.data.nowUnitName;
            this.deptName = response.data.deptName;
            if (response.data.educationalBackgrounds) {
              this.$set(this, "educationalBackgrounds", response.data.educationalBackgrounds);
            }
            if (response.data.workExperience) {
              this.$set(this, "workExperience", response.data.workExperience);
            }
            if (response.data.laborContracts) {
              this.$set(this, "laborContracts", response.data.laborContracts);
            }
            if (response.data.titles) {
              this.$set(this, "titles", response.data.titles);
            }
            if (response.data.professionalQualifications) {
              this.$set(this, "professionalQualifications", response.data.professionalQualifications);
            }
            if (response.data.rewardPunishments) {
              this.$set(this, "rewardPunishments", response.data.rewardPunishments);
            }
            if (response.data.familyMembers) {
              this.$set(this, "familyMembers", response.data.familyMembers);
            }
            if (response.data.emergencyContacts) {
              this.$set(this, "emergencyContacts", response.data.emergencyContacts);
            }

            if (response.data.dataAuthType === 1) {
              this.dataAuthNames = response.data.dataAuthNames;
              this.showDataAuthBool = true;
            } else {
              this.showDataAuthBool = false;
            }
            if (response.roleIds) {
              this.form.roleIds = response.roleIds;
            }
            if (response.userTips) {
              this.form.userTip = response.userTips;
            }
            if (this.form.userCategory) {
              this.form.userCategory = this.form.userCategory.split(",");
            }
            // 编辑初始化值
            this.$refs.userPickerRef.getAllUserList([this.form.superiorName]);
          })
          .finally(() => {
            this.formLoading = false;
          });
      }
    },
    getSysUserTip() {
      listTip().then((resp) => {
        this.userTipOptions = resp.rows;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    getTreeselectAll() {
      treeselectAll().then((response) => {
        this.deptOptions = response.data;
      });
    },

    openUserPicker() {
      this.$refs.userPickerRef.openHandler();
    },
    userPickerResult(value, data) {
      if (value && data) {
        this.form.superiorName = data[0];
        this.form.superiorId = value;
        this.backUserIds = [Number(value)];
      } else {
        this.form.superiorName = "";
        this.form.superiorId = "";
        this.backUserIds = [];
      }
    },
    openDeptHandler() {
      this.deptPickerOpen = true;
    },
    // 表单重置
    reset() {
      this.form = {
        userName: undefined,
        phonenumber: undefined,
        addPassword: undefined,
        editPassword: undefined,
        password: undefined,
        jobNumber: undefined,
        relationUnitId: undefined,
        nowUnitId: undefined,
        deptId: undefined,
        dutyName: undefined,
        entryTime: undefined,
        idcard: undefined,
        sex: "0",
        employType: undefined,
        politicsOutlook: undefined,
        joinPoliticalTime: undefined,
        superiorId: undefined,
        superiorName: undefined,
        userTip: [],
        userCategory: [],
        dataAuthType: undefined,
        dataAuthId: undefined,
        status: "0",
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.saveBtnLoading = true;
          this.form.userCategory = this.form.userCategory.join(",");
          this.form.userType = "plant";

          this.$set(this.form, "educationalBackgrounds", this.educationalBackgrounds);
          this.$set(this.form, "workExperience", this.workExperience);
          this.$set(this.form, "laborContracts", this.laborContracts);
          this.$set(this.form, "titles", this.titles);
          this.$set(this.form, "professionalQualifications", this.professionalQualifications);
          this.$set(this.form, "rewardPunishments", this.rewardPunishments);
          this.$set(this.form, "familyMembers", this.familyMembers);
          this.$set(this.form, "emergencyContacts", this.emergencyContacts);
          console.info(this.form)


          if (this.userId !== undefined) {
            if (this.form.editPassword) {
              if (
                this.form.editPassword.length < 5 ||
                this.form.editPassword.length > 20
              ) {
                this.$modal.msgError("登录密码长度必须介于 5 和 20 之间");
                this.saveBtnLoading = false;
                return;
              }
            }
            this.form.password = this.form.editPassword;
            updateUser(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                // 清空页签缓存
                this.$tab.clearKeepAlivePage("User");
                this.closeBtnHandler();
              })
              .catch(() => {
                this.form.userCategory = this.form.userCategory.split(",");
              })
              .finally(() => {
                this.saveBtnLoading = false;
              });
          } else {
            this.form.password = this.form.addPassword;
            addUser(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                // 清空页签缓存
                this.$tab.clearKeepAlivePage("User");
                this.closeBtnHandler();
              })
              .catch(() => {
                this.form.userCategory = this.form.userCategory.split(",");
              })
              .finally(() => {
                this.saveBtnLoading = false;
              });
          }
        }
      });
    },
    dataAuthTypeChangeHandler(data) {
      if (data > 0) {
        this.showDataAuthBool = true;
      } else {
        this.showDataAuthBool = false;
        this.form.dataAuthId = undefined;
      }
    },
    closeBtnHandler() {
      // 关闭当前页面
      this.$tab.closeOpenPage();
      // 刷新列表页面
      this.$tab.refreshPage({path: "/manager/user"});
    },
    openOrgTree(type) {
      this.orgIds = [];
      this.orgType = type;
      this.orgTitle =
        type == "1" ? "劳动关系所在单位" : type == "2" ? "现工作单位" : "部门";

      if (type == "1" || type == "2") {
        this.orgData = this.filterOrgData(this.deptOptions);
        if (type == "1" && this.form.relationUnitId) {
          this.orgIds = [this.form.relationUnitId];
        }
        if (type == "2" && this.form.nowUnitId) {
          this.orgIds = [this.form.nowUnitId];
        }

        this.showOrgTree = true;
      }
      if (type == "4") {
        this.orgData = this.deptOptions;
        if (this.form.dataAuthId) {
          this.orgIds = this.form.dataAuthId.split(",");
        }
        this.showOrgTree = true;
      }
      if (type == 3) {
        // 获取现工作单位下的部门
        if (!this.form.nowUnitId) {
          this.$modal.msgError("请先选择现工作单位！");
          return;
        }
        let param = {
          ancestors: this.form.nowUnitId,
        };
        getDepartments(param).then((res) => {
          if (res.code == 200) {
            this.orgData = res.data;
            this.showOrgTree = true;
            if (this.form.deptId) {
              this.orgIds = [this.form.deptId];
            }
          }
        });
      }
    },
    saveOrgValue(values) {
      this.showOrgTree = false;
      let orgName = "";
      let orgId = "";
      if (values && values.length) {
        orgName = values[0].deptName;
        orgId = values[0].id;
      }
      if (this.orgType == "1") {
        //劳动关系所在单位
        this.relationUnitName = orgName;
        this.form.relationUnitId = orgId;
      }
      if (this.orgType == "2") {
        //现工作单位
        this.nowUnitName = orgName;
        this.form.nowUnitId = orgId;
        this.form.deptId = "";
        this.deptName = "";
      }
      if (this.orgType == "3") {
        //部门
        this.deptName = orgName;
        this.form.deptId = orgId;
      }
      if (this.orgType == "4") {
        //权限部门
        if (values.length > 0) {
          this.dataAuthNames = values.map((m) => m.deptName).join(",");
          this.form.dataAuthId = values.map((m) => m.id).join(",");
        } else {
          this.orgIds = [];
          this.dataAuthNames = "";
          this.form.dataAuthId = "";
        }
      }
    },
    // 过滤组织结构前两层数据
    filterOrgData(data) {
      let orgTree = [];
      data.forEach((ditem, dindex) => {
        orgTree.push({
          id: ditem.id,
          label: ditem.label,
          children: [],
        });
        if (ditem.children && ditem.children.length) {
          ditem.children.forEach((dcitem) => {
            orgTree[dindex].children.push({
              id: dcitem.id,
              label: dcitem.label,
            });
          });
        }
      });
      return orgTree;
    },
    clearOrgValue(type) {
      if (type == "1") {
        //劳动关系所在单位
        this.relationUnitName = "";
        this.form.relationUnitId = "";
      }
      if (type == "2") {
        //现工作单位
        this.nowUnitName = "";
        this.form.nowUnitId = "";
        this.form.deptId = "";
        this.deptName = "";
      }
      if (this.orgType == "3") {
        //部门
        this.deptName = "";
        this.form.deptId = "";
      }
    },
  },
};
</script>

<style scoped lang="scss">
.titleBox{
  display: flex;
  flex-flow: row nowrap;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
  margin-bottom: 10px;
}
.label{
  width: 160px;
  font-weight: 700;
}
.columnIcon{
  font-size: 18px;
  margin-left: 10px;
  margin-top: 5px;
  cursor: pointer;
}
.org-field {
  cursor: pointer;
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  position: relative;
  color: #606266;
  padding: 0 10px;

  .icon-right {
    color: #c0c4cc;
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
  }

  .icon-close {
    opacity: 0;
    cursor: pointer;
    background-color: #c0c4cc;
    border-radius: 50%;
    font-size: 12px;
    margin-left: 5px;
  }

  .icon-close:before {
    font-size: 12px !important;
  }

  .icon-close:hover {
    color: #fff;
    background-color: #909399;
  }
}

.org-field:hover .icon-close {
  opacity: 1;
}
</style>
